package com.gzq.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.springboot.starter.upload.model.Chunk;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gzq.domain.TestUser;
import com.gzq.service.TestUserService;
import com.gzq.my.config.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.springframework.http.HttpHeaders.CONTENT_TYPE;

@RestController
@RequestMapping("testuser")
@CrossOrigin
public class UserController {


    @Autowired
    TestUserService userService;

    @Autowired
    FileService fileService;



    @RequestMapping("list")
    public List<TestUser> list(Integer pageNum,Integer pageSize){
        pageNum=(pageNum-1)*pageSize+1;
        long l = System.currentTimeMillis();
        List<TestUser> list = userService.listByPage(pageNum, pageSize);
        long l1 = System.currentTimeMillis();
        System.out.println("用时"+(l1-l)+"毫秒");
        return list;
    }




    @RequestMapping("baiwanout")
    public void  exportExcel(HttpServletResponse response) throws InterruptedException, IOException {
        setExportHeader(response);
        int count = userService.list().size();
        Integer pages=20;
        int size = count / pages;
        ExecutorService executorService = Executors.newFixedThreadPool(pages);
        CountDownLatch countDownLatch = new CountDownLatch(pages);
        Map<Integer,PageInfo<TestUser>> pageMap=new HashMap<>();
        for (int i=0;i<pages;i++){
            int finalI=i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    Page<TestUser> page = new Page<>();
                    page.setCurrent(finalI+1);
                    page.setSize(size);
                    PageHelper.startPage(finalI+1,size);
                    List<TestUser> list = userService.list();
                    PageInfo<TestUser> info = new PageInfo<>(list);
                    pageMap.put(finalI,info);
                    countDownLatch.countDown();
                }

            });
            countDownLatch.await();
            ExcelWriter build = EasyExcel.write(response.getOutputStream(), TestUser.class).build();
            for (Map.Entry<Integer, PageInfo<TestUser>> entry : pageMap.entrySet()) {
                Integer num = entry.getKey();
                PageInfo<TestUser> doPage = entry.getValue();
                WriteSheet writeSheet = EasyExcel.writerSheet(num, "模板" + num).build();
                build.write(doPage.getList(),writeSheet);

            }
            build.finish();
        }

    }
    private static void setExportHeader(HttpServletResponse response) {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "test.xlsx");
    }





    /*
    导出 合并单元格
     */
    @RequestMapping("/outDate")
    public R outDate() {
        String path = "c:/Users/Lenovo/Desktop/DateOut（合并）.xlsx";
        Integer count = userService.list().size();
        long l = System.currentTimeMillis();
        userService.outDate(path, count);
        long l1 = System.currentTimeMillis();
        return R.successed("导出用时"+(l1 - l) / 1000+"秒");
    }

    /*
    少量数据的导入
     */
    @RequestMapping("readData")
    public void readData(MultipartFile file)  {

        long l = System.currentTimeMillis();
        userService.readData(file);
        long l1 = System.currentTimeMillis();
        System.err.println("导入共用时"+(l1 - l)/1000+"秒");
    }



   /*
    大文件上传
     */
    @RequestMapping("bigupload")
    public FileResult upload(Chunk chunk) throws InterruptedException {
        System.out.println("大文件上传方法执行");
        fileService.postFileUpload(chunk);
        //定义文件路径 与配置文件定义的值相同
        String path="D:/path/";
        if (chunk.getChunkNumber() == chunk.getTotalChunks()){
            Thread.sleep(2000);
            //合并
            FileResult fileResult = fileService.mergeFile(chunk);
            String substring = fileResult.getFileUrl().substring(21);
            path=path+substring;
            userService.readDataPath(path);
            //操作成功 ，删除文件，判断是否为空
            File file = new File(path);
            if (file.isFile()&&file.exists()){
                file.delete();
            }
            return fileResult;
        }
        return null;
    }





}
